import logging
import os.path as _path
from pathlib import PurePath
from typing import Set

import yaml

from pydantic import BaseSettings

from .logger import MyLogger


PROJECT_PATH = _path.dirname(_path.realpath(_path.abspath(__file__)))
CFG_PATH = _path.join(_path.dirname(PROJECT_PATH), "cfg.yml")


class DavSettings(BaseSettings):
    LOG_LEVEL: str = 'INFO'
    ENABLE_TEST_API: bool = False
    PROXY_ADDR: str = None  # 为httpx设置代理地址
    VERIFY_CA: bool = True
    USER_PASSWD: Set[str] = set()
    LOCAL_MOUNT_PATH: PurePath = PurePath(PROJECT_PATH)
    LOCAL_ROOT_PATH: PurePath = PurePath('/')
    PAN_115_ROOT_CID: str = None
    PAN_115_COOKIE: str = None
    PAN_115_MOUNT_PATH: PurePath = None
    PAN_115_CACHE_IN_MEM: bool = False

    app_log: logging.Logger = None


def load_setting(cfg_path=CFG_PATH) -> DavSettings:
    setting = DavSettings()
    with open(cfg_path, 'r', encoding='utf-8') as f:
        cfg = yaml.load(f, yaml.FullLoader)

    setting.USER_PASSWD = {
        f"{k}:{v}" for k, v in cfg["users"].items()
    }
    setting.LOCAL_MOUNT_PATH = PurePath(cfg["local_file_mount"]["mount_path"])
    setting.LOCAL_ROOT_PATH = PurePath(cfg["local_file_mount"]["root_path"])
    if 'pan_115_mount' in cfg:
        pan_115_cfg = cfg["pan_115_mount"]
        setting.PAN_115_ROOT_CID = str(pan_115_cfg['root_cid'])
        setting.PAN_115_COOKIE = pan_115_cfg['cookie']
        setting.PAN_115_MOUNT_PATH = PurePath(pan_115_cfg['mount_path'])
        setting.PAN_115_CACHE_IN_MEM = pan_115_cfg['cache_in_memory']

    if setting.LOCAL_MOUNT_PATH and setting.PAN_115_MOUNT_PATH:
        if is_relative(setting.LOCAL_MOUNT_PATH, setting.PAN_115_MOUNT_PATH):
            raise ValueError('本地文件挂载路径和115网盘挂载路径不应有包含关系')

    if 'dev_setting' in cfg:
        dev_setting = cfg["dev_setting"]
        setting.PROXY_ADDR = dev_setting["proxy"]
        setting.VERIFY_CA = dev_setting["verify_ca"]

    if 'log_setting' in cfg:
        log_setting = cfg["log_setting"]
        setting.LOG_LEVEL = log_setting.get("log_level")
    setting.app_log = MyLogger("DavLog", setting.LOG_LEVEL).get_log()

    return setting


def is_relative(p1: PurePath, p2: PurePath) -> bool:
    flg = 2
    try:
        p1.relative_to(p2)
    except Exception:
        flg -= 1

    try:
        p2.relative_to(p1)
    except Exception:
        flg -= 1

    return bool(flg)


app_setting = load_setting()


if __name__ == '__main__':
    s = load_setting()